/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.bayu.graph;



import java.awt.Color;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.text.ParseException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.annotations.XYTextAnnotation;
import org.jfree.chart.axis.AxisLocation;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.labels.XYItemLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.CombinedDomainXYPlot;
import org.jfree.chart.plot.DatasetRenderingOrder;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.chart.renderer.xy.StandardXYItemRenderer;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.bayu.common.lib.CommonUtil;
import com.bayu.controller.MainController;

import com.bayu.services.dao.ExchangeCurrencyImpl;
import com.bayu.services.dao.RejectGalvaImpl;
import com.bayu.services.entity.ExchangeCurrency;
import com.bayu.services.entity.RejectGalva;
import java.awt.Font;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.jfree.chart.axis.NumberAxis3D;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.labels.StandardXYItemLabelGenerator;
import org.jfree.chart.renderer.category.CategoryItemRenderer;
import org.jfree.data.category.CategoryDataset;
import org.jfree.ui.TextAnchor;
import org.springframework.beans.factory.annotation.Autowired;
/**
 *
 * @author Bayu
 */
@Controller
public class DemoChartController {
  private ExchangeCurrencyImpl exchangeCurrencyDao;
  
  
  @Autowired
  private void setExchangeCurrencyDao(ExchangeCurrencyImpl exchangeCurrencyDao){
      this.exchangeCurrencyDao = exchangeCurrencyDao;
      
  }


  @RequestMapping("/rpusd.png")
  public void rpUsdGraph(OutputStream stream) throws Exception {
    List maxValue= exchangeCurrencyDao.custom("select max(rpusd) from ExchangeCurrency where date between '"+MainController.startDate+"' and '"+MainController.endDate+"'");
    List minValue = exchangeCurrencyDao.custom("select min(rpusd) from ExchangeCurrency where date between '"+MainController.startDate+"' and '"+MainController.endDate+"'");
    String strMin = minValue.get(0).toString();
    String strMax = maxValue.get(0).toString();
    System.out.println(strMin+"-"+strMax);
    double min = Double.valueOf(strMin).doubleValue()-100.0;
    double max = Double.valueOf(strMax).doubleValue()+100.0;
    //boolean rotate = "rotate".equals(variation); // add ?variation=rotate to the URL to rotate the chart
    JFreeChart chart = exchangeCurrencyGraph("RP/1 USD", "RP up(down)", "rpusd", "RP / 1 USD", "Date", "RP",min,max);
    ChartUtilities.writeChartAsPNG(stream, chart, 1480,800);
  }
 @RequestMapping("/rpjpy.png")
 public void rpJpyGraph(OutputStream stream) throws Exception {
    List maxValue= exchangeCurrencyDao.custom("select max(rpjpy) from ExchangeCurrency where date between '"+MainController.startDate+"' and '"+MainController.endDate+"'");
    List minValue = exchangeCurrencyDao.custom("select min(rpjpy) from ExchangeCurrency where date between '"+MainController.startDate+"' and '"+MainController.endDate+"'");
    String strMin = minValue.get(0).toString();
    String strMax = maxValue.get(0).toString();
    System.out.println(strMin+"-"+strMax);
    double min = Double.valueOf(strMin).doubleValue()-100.0;
    double max = Double.valueOf(strMax).doubleValue()+100.0;
    
    JFreeChart chart = exchangeCurrencyGraph("RP/100 JPY", "RP up(down)", "rpjpy", "RP / 100 JPY", "Date", "RP",min,max);
    ChartUtilities.writeChartAsPNG(stream, chart, 1480,800);
 }
@RequestMapping("/jpyusd.png")
 public void jpyUsdGraph(OutputStream stream) throws Exception {
    List maxValue= exchangeCurrencyDao.custom("select max(jpyusd) from ExchangeCurrency where date between '"+MainController.startDate+"' and '"+MainController.endDate+"'");
    List minValue = exchangeCurrencyDao.custom("select min(jpyusd) from ExchangeCurrency where date between '"+MainController.startDate+"' and '"+MainController.endDate+"'");

     String strMin = minValue.get(0).toString();
    String strMax = maxValue.get(0).toString();
    System.out.println(strMin+"-"+strMax);
    double min = Double.valueOf(strMin).doubleValue()-100.0;
    double max = Double.valueOf(strMax).doubleValue()+100.0;

    JFreeChart chart = exchangeCurrencyGraph("JPY/1 USD", "JPY up(down)", "usdjpy", "JPY/1 USD", "Date", "JPY",min,max);
    ChartUtilities.writeChartAsPNG(stream, chart, 1480,800);
 }



 @RequestMapping("/currencyexchagelinechart.png")
  public void renderDualLine(OutputStream stream) throws Exception {
    //boolean rotate = "rotate".equals(variation); // add ?variation=rotate to the URL to rotate the chart
    List maxValue= exchangeCurrencyDao.custom("select max(rpjpy) from ExchangeCurrency where date between '"+MainController.startDate+"' and '"+MainController.endDate+"'");
    List minValue = exchangeCurrencyDao.custom("select min(rpusd) from ExchangeCurrency where date between '"+MainController.startDate+"' and '"+MainController.endDate+"'");

     String strMin = minValue.get(0).toString();
    String strMax = maxValue.get(0).toString();
    System.out.println(strMin+"-"+strMax);
    double min = Double.valueOf(strMin).doubleValue()-100.0;
    double max = Double.valueOf(strMax).doubleValue()+100.0;

    JFreeChart chart3 =createLineGraph(min,max);
    ChartUtilities.writeChartAsPNG(stream, chart3, 1480,800);
  }
  private JFreeChart exchangeCurrencyGraph(String rowValue1,String rowValue2,String strGraph,String chartTitle,String domainAxisLabel,String rangeAxisLabel,Double min,Double max) throws IOException{
      String tgl1="";
      String tgl2="";
      //String title = "Foreign Exchange Currency";

      if(!MainController.startDate.equals("")){
          tgl1 = CommonUtil.formatStringDate(MainController.startDate);
          tgl2 = CommonUtil.formatStringDate(MainController.endDate);
            chartTitle = chartTitle+"\r\n"+ tgl1+"-"+tgl2;
      }
      DefaultCategoryDataset dataset1 = createDataSet1(rowValue1,strGraph);
       final JFreeChart chart = ChartFactory.createBarChart(
            chartTitle,        // chart title
           domainAxisLabel,               // domain axis label
           rangeAxisLabel,                  // range axis label
            dataset1,                 // data
            PlotOrientation.VERTICAL,
            true,                     // include legend
            true,                     // tooltips?
            false                     // URL generator?  Not required...
        );

        chart.setBackgroundPaint(new Color(255, 255, 255));
        CategoryPlot plot = chart.getCategoryPlot();

        plot.setDomainAxisLocation(AxisLocation.BOTTOM_OR_LEFT);
        plot.setRangeAxisLocation(AxisLocation.TOP_OR_LEFT);
        CategoryItemRenderer renderer1 = plot.getRenderer();
        renderer1.setSeriesPaint(0, new Color(153,51,102));
        renderer1.setBaseNegativeItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.INSIDE12, TextAnchor.TOP_CENTER));
        renderer1.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
        renderer1.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_CENTER));
        renderer1.setBaseItemLabelsVisible(true);

      
        

        DefaultCategoryDataset dataset2 = createDataSet2(rowValue2,strGraph);
        ValueAxis axis2 = new NumberAxis3D("Up/Down");
        plot.setRangeAxis(1, axis2);
        plot.setDataset(1, dataset2);
        plot.mapDatasetToRangeAxis(1, 1);
        CategoryItemRenderer renderer2 = new LineAndShapeRenderer();
        renderer2.setSeriesPaint(0, Color.blue);
        renderer2.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
        renderer2.setBaseItemLabelsVisible(true);
        plot.setRenderer(1, renderer2);

        plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);

        NumberAxis rangeAxis = (NumberAxis)plot.getRangeAxis();
        //Set Minimum dan Maximum Value Axis
        rangeAxis.setRange(min, max);
        
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

       
        return chart;

  }
  private JFreeChart createLineGraph(double min,double max) throws IOException{
      CategoryDataset dataset1 = createLineDataset1();
      String tgl1="";
      String tgl2="";
      String title = "Foreign Exchange Currency";

      if(!MainController.startDate.equals("")){
          tgl1 = CommonUtil.formatStringDate(MainController.startDate);
          tgl2 = CommonUtil.formatStringDate(MainController.endDate);
          title = title+"\r\n"+ tgl1+"-"+tgl2;
      }
      

        
      
      
      JFreeChart chart;
      chart = ChartFactory.createLineChart(
              title,
              "Date",
              "Rp",
              dataset1,
              PlotOrientation.VERTICAL,
              true,
              true,
              false);

      chart.setBackgroundPaint(new Color(255, 255, 255));
      CategoryPlot plot = chart.getCategoryPlot();
      plot.setDomainAxisLocation(AxisLocation.BOTTOM_OR_LEFT);
      plot.setRangeAxisLocation(AxisLocation.TOP_OR_LEFT);
      CategoryItemRenderer renderer1 = plot.getRenderer();
      renderer1.setBaseNegativeItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.INSIDE12, TextAnchor.TOP_CENTER));
      renderer1.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
      renderer1.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_CENTER));
      renderer1.setBaseItemLabelsVisible(true);
      
      
      //Dataset 2 untuk axis yang baru ( Sebelah kanan)
      CategoryDataset dataset2 = createLineDataset2();
      ValueAxis axis2 = new NumberAxis("JPY");
      axis2.setAutoRange(false);
      axis2.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
      
      
      //Set Min and Max Value Axis 2
    List maxValue= exchangeCurrencyDao.custom("select max(jpyusd) from ExchangeCurrency where date between '"+MainController.startDate+"' and '"+MainController.endDate+"'");
    List minValue = exchangeCurrencyDao.custom("select min(jpyusd) from ExchangeCurrency where date between '"+MainController.startDate+"' and '"+MainController.endDate+"'");

    String strMin = minValue.get(0).toString();
    String strMax = maxValue.get(0).toString();
    System.out.println(strMin+"-"+strMax);
    double minV = Double.valueOf(strMin).doubleValue()-10.0;
    double maxV = Double.valueOf(strMax).doubleValue()+10.0;

    axis2.setRange(minV, maxV);
     

      plot.setRangeAxis(1, axis2);

    plot.setDataset(1, dataset2);
    plot.mapDatasetToRangeAxis(1, 1);
    CategoryItemRenderer renderer2 = new LineAndShapeRenderer();
    renderer2.setSeriesPaint(0, Color.BLUE);
    renderer2.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
    renderer2.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_CENTER));
    renderer2.setBaseItemLabelsVisible(true);
    plot.setRenderer(1, renderer2);

    plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);

    NumberAxis rangeAxis = (NumberAxis)plot.getRangeAxis();
    rangeAxis.setAutoRange(false);
    rangeAxis.setRange(min, max);
    rangeAxis.setMinorTickCount(10);
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    

      return chart;
  }

 
  private DefaultCategoryDataset createDataSet1(String rowValue,String strGraph) throws IOException{

      double value = 0;
      //String query = "from ExchangeCurrency where MONTH(date)='"+MainController.month+"' and YEAR(date)='"+MainController.year+"' order by date asc";
      List data = this.exchangeCurrencyDao.getAllByDate(MainController.startDate, MainController.endDate);

      DefaultCategoryDataset data1 = new DefaultCategoryDataset();

      for(int i=0;i<data.size();i++){
          ExchangeCurrency dt = (ExchangeCurrency)data.get(i);
          //String tempStr = dt.getDate().getMonth();
          if(strGraph.equals("rpusd")){
              value = dt.getRpusd();
              
          }
          if(strGraph.equals("rpjpy")){
              value = dt.getRpjpy();
          }

          if(strGraph.equals("usdjpy")){
              value = dt.getJpyusd();
          }

          String cat[] = dt.getDate().toString().split("-");
          data1.addValue(value, rowValue, cat[2]);

          System.out.println("Value : "+value+"--- date : "+cat[2]);


      }

             
   
           
      return data1;
  }

   private DefaultCategoryDataset createDataSet2(String rowValue,String strGraph)  throws IOException{
      double initValue = 0 , value = 0;

      DefaultCategoryDataset data2 = new DefaultCategoryDataset();
      //String query = "from ExchangeCurrency where MONTH(date)='"+MainController.month+"' and YEAR(date)='"+MainController.year+"' order by date asc";
      List list1 = this.exchangeCurrencyDao.getAllByDate(MainController.startDate, MainController.endDate);
      List list2 = this.exchangeCurrencyDao.getAllByDate(MainController.startDate, MainController.endDate);
      if(list1.size() > 0 ){
        ExchangeCurrency ec = (ExchangeCurrency) list1.get(0);
      
          if(strGraph.equals("rpusd")){
                initValue = ec.getRpusd();
          }
          if(strGraph.equals("rpjpy")){
                initValue = ec.getRpjpy();
          }

          if(strGraph.equals("usdjpy")){
                initValue = ec.getJpyusd();
          }
      }

      for(int i=0;i<list2.size();i++){
            ExchangeCurrency ec2 = (ExchangeCurrency) list2.get(i);

            if(strGraph.equals("rpusd")){
                value = ec2.getRpusd()-initValue;
            }
            if(strGraph.equals("rpjpy")){
                value = ec2.getRpjpy()-initValue;
            }

            if(strGraph.equals("usdjpy")){
                value = ec2.getJpyusd()-initValue;
            }
            String cat[] = ec2.getDate().toString().split("-");
            data2.addValue(value, rowValue, cat[2]);

            System.out.println("Value : "+value+"--- date : "+cat[2]);
      }
        

      return data2;
  }

  private CategoryDataset createLineDataset1() throws IOException{
      String name1="Rp/1 USD";
      String name2="Rp/100 JPY";
      DefaultCategoryDataset dataset = new DefaultCategoryDataset();
      //String query = "from ExchangeCurrency where MONTH(date)='"+MainController.month+"' and YEAR(date)='"+MainController.year+"' order by date asc";
      List list = this.exchangeCurrencyDao.getAllByDate(MainController.startDate, MainController.endDate);

      for(int i=0;i<list.size();i++){
        ExchangeCurrency ec = (ExchangeCurrency) list.get(i);
        String cat[] = ec.getDate().toString().split("-");
        dataset.addValue(ec.getRpusd(), name1, cat[2]);
        dataset.addValue(ec.getRpjpy(), name2, cat[2]);
         System.out.println("Value : "+ec.getRpusd()+"--- date : "+cat[2]);

      }

      return dataset;
  }

  private CategoryDataset createLineDataset2() throws IOException{
      String name ="JPY / 1 USD";
      DefaultCategoryDataset dataset = new DefaultCategoryDataset();
       String query = "from ExchangeCurrency where MONTH(date)='"+MainController.month+"' and YEAR(date)='"+MainController.year+"' order by date asc";
       List list = this.exchangeCurrencyDao.getAllByDate(MainController.startDate, MainController.endDate);

      for(int i=0;i<list.size();i++){
        ExchangeCurrency ec = (ExchangeCurrency) list.get(i);
        String cat[] = ec.getDate().toString().split("-");
        dataset.addValue(ec.getJpyusd(), name, cat[2]);
        System.out.println("Value : "+ec.getRpusd()+"--- date : "+cat[2]);
        
      }
      return dataset;
  }
 

}